import {
  Card,
  Button,
  Tabs,
  Drawer,
  Form,
  Space,
  Tree,
  Spin,
  message,
  Badge,
} from "antd";
import NTable from "@/components/n-table/index.jsx";
import { EditOutlined, EyeOutlined } from "@ant-design/icons";
import { useState, useEffect, useId, useMemo, Fragment } from "react";
import RoleDrawer from "./AddRole";
import {
  AddRole,
  changeStatusRole,
  deleteRole,
  GetRoleDetail,
  GetRoleList,
  UpdateRole,
} from "@/api/modules/role";
import { RoleListType } from "./types";
// @ts-ignore
import { STable, SButton, SForm } from "@cnjingx/antd-components";
import { msg, processReq } from "@/utils/util";
import { treeMap } from "@/utils/util.js";
import { menuItems } from "@/router/main";
import { isEmpty, to, toArray, treeEach } from "wsp-toolkit";

export function Component() {
  const [form] = Form.useForm();
  const [tableForm] = Form.useForm();
  const [page, setPage] = useState(1);
  const [loading, setLoading] = useState(false);
  const [open, setOpen] = useState(false);
  const [checkedMenuKeys, setCheckedMenuKeys] = useState<string[]>([]);
  const [spinning, setSpinning] = useState(false);

  const columns = [
    {
      title: "角色名称",
      key: "roleName",
      dataIndex: "roleName",
    },
    {
      title: "角色编号",
      key: "roleId",
      dataIndex: "roleId",
    },
    {
      title: "菜单",
      key: "menuStr",
      dataIndex: "menuStr",
      render: (menuStr: string) => {
        if (isEmpty(menuStr)) return "";
        const menuPathList = menuStr.split(",");
        const showMenu: string[] = [];
        treeEach(menuItems as any[], (item, index, list, level, parent) => {
          if (isEmpty(item.children) && menuPathList.includes(item.path)) {
            showMenu.push(item.label);
          }
          return item;
        });
        return showMenu.join(",");
      },
    },
    {
      title: "状态",
      key:"status",
      dataIndex: "status",
      render: (t: string) => {
        return t === "0" ? (
          <Badge status="success" text={"启用"} />
        ) : (
          <Badge status="error" text={"停用"} />
        );
      },
    },
    {
      title: "操作",
      key: "action",
      render: (_: any, row: any) => actionBtns(row),
    },
  ];

  const formItems = [
    {
      label: "roleId",
      name: "roleId",
      hidden: true,
    },
    {
      label: "角色名称",
      name: "roleName",
      required: true,
    },
  ];

  const treeData = treeMap(menuItems, (x: any) => {
    return {
      title: x.label,
      key: x.path,
      children: x.children,
    };
  });

  const isEdit = () => !isEmpty(form.getFieldValue("roleId"));

  async function handleEdit(row: any) {
    form.setFieldsValue({
      roleId: row.roleId,
    });
    setOpen(true);
    setSpinning(true);
    const [err, data] = await processReq(
      GetRoleDetail({
        roleId: row.roleId,
      }),
    );
    setSpinning(false);
    if (err) {
      msg.error(err);
      return;
    }
    form.setFieldsValue({
      roleName: data.roleName,
    });
    setCheckedMenuKeys(toArray(data.menuStr?.split(",")));
  }

  const actionBtns = (row: any) => [
    <SButton
      key="edit"
      type="link"
      size="small"
      /* icon={<EyeOutlined />} */ onClick={() => {
        return handleEdit(row);
      }}
    >
      修改
    </SButton>,
    <SButton
      danger={row.status === "0"}
      type={"link"}
      size={"small"}
      onClick={async () => {
        const [err] = await processReq(
          changeStatusRole({
            roleId: row.roleId,
            status: row.status === "0" ? "1" : "0",
          }),
        );
        if (err) {
          msg.error(err);
          return;
        }
        queryFn(page, form.getFieldsValue());
      }}
    >
      {row.status === "0" ? "停用" : "启用"}
    </SButton>,
    <SButton
      danger
      key="del"
      type="link"
      size="small"
      /* icon={<EditOutlined />} */ onClick={async () => {
        const [err] = await processReq(
          deleteRole({
            roleId: row.roleId,
          }),
        );
        if (err) {
          msg.error(err);
          return;
        }
        message.success("删除角色成功");
        resetQuery();
      }}
    >
      删除
    </SButton>,
  ];

  const searchFormBtn = () => {
    return (
      <div
        className={"pb-8"}
        style={{ display: "flex", justifyContent: "flex-end" }}
      >
        <Button key="add" type="primary" onClick={() => setOpen(true)}>
          新增
        </Button>
      </div>
    );
  };

  const queryFn = (pageNum: number, query?: any) => {
    setLoading(true);
    GetRoleList({
      pageSize: 30,
      pageNum,
      ...query,
    })
      .then(({ data }) => {
        setDatasource(data.data);
        setTotals(data.total);
        setPage(pageNum);
      })
      .catch((e) => {
        msg.error(e);
      })
      .finally(() => {
        setLoading(false);
      });
  };

  const [dataSource, setDatasource] = useState<RoleListType[]>([]);
  const [totals, setTotals] = useState(0);

  const onClose = () => {
    setOpen(false);
    setCheckedMenuKeys([]);
    form.resetFields();
  };

  useEffect(() => {
    queryFn(1);
  }, []);

  function resetQuery() {
    tableForm.setFieldsValue({
      roleName: "",
    });
    queryFn(1);
  }

  async function handleSubmit() {
    const [err, data] = await to(form.validateFields());
    if (err) return;
    const [err2] = await processReq(
      isEdit()
        ? UpdateRole({
            ...data,
            menuStr: toArray(checkedMenuKeys).join(","),
          })
        : AddRole({
            ...data,
            menuStr: toArray(checkedMenuKeys).join(","),
          }),
    );
    if (err2) {
      msg.error(err2);
      return;
    }
    message.success("操作成功");
    onClose();
    resetQuery();
  }

  return (
    <Fragment key={useId()}>
      <STable
        form={tableForm}
        loading={loading}
        columns={columns}
        formItems={[
          {
            label: "角色名称",
            name: "roleName",
          },
        ]}
        dataSource={dataSource}
        total={totals}
        page={page}
        onChange={(current: number) => {
          queryFn(current, tableForm.getFieldsValue());
        }}
        onSearch={() => {
          queryFn(1, tableForm.getFieldsValue());
        }}
        onReset={resetQuery}
      >
        {searchFormBtn()}
      </STable>
      <Drawer
        title={`${isEdit() ? "修改" : "新增"}角色`}
        placement="right"
        size={"large"}
        onClose={onClose}
        open={open}
        maskClosable={false}
        forceRender
        footer={
          <div className={"flex"} style={{ justifyContent: "flex-end" }}>
            <Space>
              <SButton onClick={onClose}>取消</SButton>
              <SButton type="primary" onClick={handleSubmit}>
                确认
              </SButton>
            </Space>
          </div>
        }
      >
        <Spin spinning={spinning}>
          <SForm
            layout={"vertical"}
            formItems={formItems}
            columnRepeat={1}
            form={form}
          ></SForm>
          <div>
            <div style={{ marginBottom: 24 }}>菜单</div>
            <Tree
              treeData={treeData}
              checkable
              defaultExpandAll
              checkedKeys={checkedMenuKeys}
              onCheck={(keys: any) => {
                setCheckedMenuKeys(keys);
              }}
            />
          </div>
        </Spin>
      </Drawer>
    </Fragment>
  );
}
